<?php

namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Builder;

class Post extends BaseModel
{
    //use SoftDeletes;  

    /**
     * 与模型关联的表名
     * @var string
     */
    protected $table = 'posts';
    protected $listHidden = 'conntent';
    protected $includes = ['cate', 'user', 'user.posts'];

    //复用表
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        static::addGlobalScope("avaiable", function (Builder $builder){
            $builder->where('mslug', get_class($this));
        });
        $this->setAttribute('mslug', get_class($this));
    }    
    
    //复用表，防错误追加,强制设置
    public function setMslugAttribute($value)
    {
        $this->attributes['mslug'] = get_class($this);
    }


    public function user()
    {
        return $this->belongsTo(\App\Models\User::class, 'user_id');
    }

    public function cate()
    {
        return $this->belongsTo(\App\Modules\Post\Models\PostCate::class, 'cate_id');
    }

    public function scopePosition($qquery, $pos = '')
    {
        if ($pos) {
            $query = $qquery->whereRaw('FIND_IN_SET(?,pos)', str2arr($pos));
        }
        return $query;
    }

    public function scopeCreateBetween($query, $time = 0)
    {
        $timearr = str2arr($time);
        if (count($timearr) === 2) {
            $query = $query->whereBetween('created_at', $timearr);
        } else {
            $query = $query->whereDate('created_at', '=', $time);
        }
        return $query;
    }
}
